package com.cookman.factories;

import com.cookman.gameobjects.CityActor;
import com.cookman.ioc.ConfigReader;
import com.cookman.world.entities.City;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;

import java.util.List;

/**
 * Created by Cookman on 05.05.14.
 */
public class CitiesFactory {

    private CitiesFactory() {
    }

    private static ConfigReader configReader = new ConfigReader();
    private static List<CityActor> cities;

    public static List<CityActor> getCities() {
        return cities;
    }

    public static void loadCities(List<City> gameCities) {
        XStreamTranslator translator = new XStreamTranslator();
        translator.xstream.alias("cities", WorldCityList.class);
        translator.xstream.addImplicitCollection(WorldCityList.class, "cities");
        WorldCityList citiesList = (WorldCityList) translator.xstream.fromXML(configReader.readFile("/worldcities.xml"));
        cities = citiesList.getCities();
        for (CityActor cityActor : cities) {
            City city = findById(gameCities, cityActor.getId());
            cityActor.setCity(city);
        }
    }

    public static City findById(List<City> gameCities, String id) {
        for (City city : gameCities) {
            if (city.getId().equals(id)) {
                return city;
            }
        }
        return null;
    }

    public static CityActor findWorldCityById(String id) {
        for (CityActor city : cities) {
            if (city.getId().equals(id)) {
                return city;
            }
        }
        return null;
    }

    public static final class XStreamTranslator {
        private XStream xstream = null;

        private XStreamTranslator() {
            xstream = new XStream(new PureJavaReflectionProvider());
            xstream.ignoreUnknownElements();
        }
    }

    public static class WorldCityList {
        private List<CityActor> cities;

        public WorldCityList() {
        }

        public WorldCityList(List<CityActor> cities) {
            this.cities = cities;
        }

        public List<CityActor> getCities() {
            return cities;
        }
    }
}
